package net.jxtz.jxtzos.authentication;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.auth.Role;
import net.jxtz.jxtzos.entity.auth.User;
import net.jxtz.jxtzos.mapper.auth.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 封装用户信息以及角色信息类
 * @author a123
 */

@Slf4j
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    /**
     * 封装用户信息以及角色信息
     * @param s 前端传来的用户名
     * @return UserDetails
     * @throws UsernameNotFoundException 用户名找不到异常
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.info("用户信息正在封装");
        // 根据回调参数查询用户所有信息
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", s));
        if (user == null){
            String error = "用户不存在";
            log.error(error);
            throw new UsernameNotFoundException(error);
        }

        // 根据用户id查询所有角色
        List<Role> roles = userMapper.getRolesByUserId(user.getId());
        // 封装角色信息
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        log.info("正在封装用户角色信息");
        for (Role role : roles) {
            String newRoleName = "ROLE_" + role.getRoleName();
            authorities.add(new SimpleGrantedAuthority(newRoleName));
        }

        // 构建 Security的 用户信息对象并返回
        log.info("用户信息封装完毕");
        // 自定义实现的UserDetails
        return new MyUserDetails(user.getId(), user.getUserName(), user.getPassword(), authorities, user.getNikeName(), user.getHeadUrl());
    }

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper){
        this.userMapper = userMapper;
    }
}
